package cn.ipanel.bigdata.boot

import cn.ipanel.bigdata.boot.date.Time
import cn.ipanel.bigdata.boot.logger.Logger
import cn.ipanel.bigdata.utils.Util._
import org.apache.commons.lang3.exception.ExceptionUtils

/**
 * Author: lzz
 * Date: 2021/11/16 16:15
 */
object Application {

  private[boot] val RESULT_SUCCESS        : Int = 0
  private[boot] val RESULT_PARAM_INVALID  : Int = 404
  private[boot] val RESULT_FAILURE        : Int = 500
  private[boot] val RESULT_EXCEPTION      : Int = 510
  private[boot] val RESULT_TIMEOUT        : Int = 800

  private[this] var job: Job = _
  private[this] var now: Time = Time.now
  def getExecJobName: String = if (isNull(job)) null else job.getJobName

  private[boot] def shutdown(code: Int): Unit = {
    Logger.I(s"application shutdown. exit code = $code, use time = ${now.diffToNow / 1000}sec")
    // TODO Yarn模式下，这里会有问题
    // System.exit(code)
    job.saveJobStat(code)
  }

  private[boot] final def started(): Int = {
    val monitor: JobMonitor = new JobMonitor(job.getJobName, job.maxRuntime)
    try {
//      monitor.open()
      job.onPrepare()
      job.onStartup()
      if (job.onFruited()) RESULT_SUCCESS else RESULT_FAILURE
    } catch {
      case e: Exception =>
        Logger.E(
          s""" execute Job[${job.getJobName}] failed.
             | Because: ${ExceptionUtils.getStackTrace(e)}
             |""".stripMargin)
        RESULT_EXCEPTION
    } finally {
      try {
        job.onDestroy()
//        monitor.quit()
      } catch {
        case e: Exception =>
          Logger.E(
            s""" destroy Job[${job.getJobName}] failed.
               | Because: ${ExceptionUtils.getStackTrace(e)}
               |""".stripMargin)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    now = Time.now
    if (args.length < 1)
      shutdown(RESULT_PARAM_INVALID)
    else {
      val param: String = args(0)
      Logger.I(s"application startup. accept param = $param")
      job = Job(Bundle.build(param))
      if (isNull(job))
        shutdown(RESULT_PARAM_INVALID)
      else
        shutdown(started())
    }
  }
}